// 异动解析Vue组件
const ActionComponent = {
    template: `
        <div class="action-page">
            <div class="page-header">
                <h2>异动解析</h2>
                <div class="header-actions">
                    <input 
                        type="date" 
                        v-model="selectedQueryDate"
                        style="margin-right: 10px; padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;"
                        @change="handleDateChange">
                    <el-button type="primary" @click="queryByDate" :loading="loading">
                        <i class="el-icon-search"></i>
                        查询
                    </el-button>
                    <el-button @click="loadRecentData" :loading="loading">
                        <i class="el-icon-refresh"></i>
                        最近数据
                    </el-button>
                </div>
            </div>

            <!-- 查询状态提示 -->
            <div class="query-status">
                <el-alert
                    v-if="currentQueryType === 'recent'"
                    title="正在显示最近日期的异动解析数据"
                    type="success"
                    :closable="false"
                    show-icon>
                </el-alert>
                <el-alert
                    v-else-if="currentQueryType === 'date' && selectedQueryDate"
                    :title="'正在显示 ' + selectedQueryDate + ' 的异动解析数据'"
                    type="info"
                    :closable="false"
                    show-icon>
                </el-alert>
            </div>

            <div class="action-container">
                <div class="left-panel">
                    <div class="tree-container">
                        <el-tree
                            :data="treeData"
                            :props="treeProps"
                            node-key="actionFieldId"
                            :default-expand-all="false"
                            :expand-on-click-node="true"
                            :default-expanded-keys="[]"
                            @node-click="handleNodeClick"
                            @node-expand="handleNodeExpand"
                            @node-collapse="handleNodeCollapse"
                            class="action-tree">
                            <template #default="{ node, data }">
                                <span class="tree-node">
                                    <i v-if="!node.isLeaf" :class="node.expanded ? 'el-icon-folder-opened' : 'el-icon-folder'" 
                                       style="margin-right: 5px; color: #409eff;"></i>
                                    <i v-else class="el-icon-document" style="margin-right: 5px; color: #67c23a;"></i>
                                    <span class="node-label" v-if="!node.isLeaf">{{ data.name }}</span>
                                    <span class="node-label" v-else v-html="formatStockNodeName(data.name)"></span>
                                    <span v-if="!node.isLeaf" class="node-count">({{ data.count || 0 }})</span>
                                </span>
                            </template>
                        </el-tree>
                    </div>
                </div>

                <div class="right-panel">
                    <div v-if="selectedField" class="detail-container">
                        <div class="detail-header">
                            <h3>{{ selectedField.name }}</h3>
                            <div class="header-info">
                                <span v-if="selectedField.date" class="info-item">日期: {{ selectedField.date }}</span>
                                <span v-if="selectedField.count && selectedField.count > 1" class="info-item">股票数量: {{ selectedField.count }}</span>
                                <span v-if="selectedField.reason" class="info-item">原因: {{ selectedField.reason }}</span>
                                <span v-if="selectedField.list && selectedField.list.length === 1 && selectedField.list[0].code" class="info-item">股票代码: {{ selectedField.list[0].code }}</span>
                            </div>
                        </div>

                        <div class="stock-list" v-if="selectedField.list && selectedField.list.length > 0">
                            <div v-for="stock in selectedField.list" :key="stock.code" class="stock-item">
                                <div class="stock-header">
                                    <h4>{{ stock.name }} ({{ stock.code }})</h4>
                                    <div class="stock-meta">
                                        <span v-if="stock.article.actionInfo.time" class="time">
                                            <i class="el-icon-time"></i>
                                            {{ stock.article.actionInfo.time }}
                                        </span>
                                        <span v-if="stock.article.actionInfo.num" class="num">
                                            <i class="el-icon-s-data"></i>
                                            {{ stock.article.actionInfo.num }}
                                        </span>
                                        <span v-if="stock.article.actionInfo.price" class="price">
                                            <i class="el-icon-coin"></i>
                                            ¥{{ (stock.article.actionInfo.price / 100).toFixed(2) }}
                                        </span>
                                    </div>
                                </div>
                                
                                <div class="article-info">
                                    <h5>{{ stock.article.title }}</h5>
                                    <div class="article-meta">
                                        <span><i class="el-icon-view"></i> {{ stock.article.likeCount }}点赞</span>
                                        <span><i class="el-icon-chat-line-square"></i> {{ stock.article.commentCount }}评论</span>
                                        <span><i class="el-icon-share"></i> {{ stock.article.forwardCount }}转发</span>
                                        <span><i class="el-icon-time"></i> {{ stock.article.createTime }}</span>
                                    </div>
                                </div>

                                <div v-if="stock.article.actionInfo.expound" class="expound-content">
                                    <p>{{ stock.article.actionInfo.expound }}</p>
                                </div>

                                <div class="action-tags">
                                    <el-tag v-if="stock.article.actionInfo.isCrawl" type="info" size="small">爬取数据</el-tag>
                                    <el-tag v-if="stock.article.actionInfo.isRecommend" type="warning" size="small">推荐</el-tag>
                                    <el-tag v-if="stock.article.actionInfo.day" type="primary" size="small">
                                        {{ stock.article.actionInfo.day }}天
                                    </el-tag>
                                    <el-tag v-if="stock.article.actionInfo.edition" type="success" size="small">
                                        {{ stock.article.actionInfo.edition }}版
                                    </el-tag>
                                </div>
                            </div>
                        </div>

                        <el-empty v-else description="暂无股票异动数据" :image-size="200"></el-empty>
                    </div>

                    <div v-else class="welcome-panel">
                        <el-empty description="请从左侧选择异动领域查看详细信息" :image-size="200">
                            <i class="el-icon-data-analysis" style="font-size: 48px; color: #c0c4cc;"></i>
                        </el-empty>
                    </div>
                </div>
            </div>

            <!-- 统计信息 -->
            <div class="statistics-panel" v-if="actionData.length > 0">
                <h3>统计信息</h3>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">异动领域数量</div>
                            <div class="stat-value">{{ actionData.length }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">总股票数量</div>
                            <div class="stat-value">{{ getTotalStockCount() }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">选中领域</div>
                            <div class="stat-value">{{ selectedField ? selectedField.name : '-' }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card class="stat-card">
                            <div class="stat-title">最后更新时间</div>
                            <div class="stat-value">{{ lastUpdateTime }}</div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </div>
    `,
    
    data() {
        // 获取当前日期并格式化为YYYY-MM-DD
        const today = new Date();
        const currentDate = today.getFullYear() + '-' + 
                          String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                          String(today.getDate()).padStart(2, '0');
        
        return {
            loading: false,
            lastUpdateTime: new Date().toLocaleString(),
            selectedQueryDate: currentDate,
            currentQueryType: 'date', // 'recent', 'date' - 改为date以默认加载当前日期数据
            actionData: [],
            selectedField: null,
            treeProps: {
                children: 'children',
                label: 'name'
            }
        }
    },
    
    computed: {
        treeData() {
            return this.actionData.map(field => ({
                actionFieldId: field.actionFieldId,
                name: field.name,
                date: field.date,
                reason: field.reason,
                count: field.count,
                list: field.list,
                children: field.children || [] // 确保包含children字段
            }));
        }
    },
    
    methods: {
        async refreshData() {
            this.loading = true;
            try {
                await this.loadActionData();
                this.lastUpdateTime = new Date().toLocaleString();
            } finally {
                this.loading = false;
            }
        },
        
        async loadActionData() {
            try {
                let url;
                if (this.currentQueryType === 'date' && this.selectedQueryDate) {
                    // 格式化日期为yyyyMMdd
                    //const formattedDate = this.selectedQueryDate.replace(/-/g, '');
                    const formattedDate = this.selectedQueryDate;
                    url = `/api/action/${formattedDate}`;
                    console.log('正在请求指定日期异动解析数据URL:', url);
                } else {
                    url = `/api/action/get`;
                    console.log('正在请求异动解析数据URL:', url);
                }
                
                const response = await axios.get(url);
                console.log('异动解析数据API响应:', response.data);
                
                if (response.data && response.data.code === 200) {
                    const actionData = response.data.data || [];
                    this.processActionData(actionData);
                    console.log('成功加载异动解析数据');
                } else if (Array.isArray(response.data)) {
                    // 直接返回数组的情况
                    this.processActionData(response.data);
                    console.log('成功加载异动解析数据');
                } else {
                    console.error('异动解析数据格式异常:', response.data);
                }
            } catch (error) {
                console.error('加载异动解析数据失败:', error);
                if (window.ElMessage) {
                    window.ElMessage.error('数据加载失败: ' + (error.response?.data?.message || error.message));
                }
            }
        },
        
        async queryByDate() {
            if (!this.selectedQueryDate) {
                if (window.ElMessage) {
                    window.ElMessage.warning('请选择查询日期');
                }
                return;
            }
            
            this.currentQueryType = 'date';
            this.selectedField = null;
            await this.refreshData();
        },
        
        async loadRecentData() {
            this.currentQueryType = 'recent';
            this.selectedQueryDate = null;
            this.selectedField = null;
            await this.refreshData();
        },
        
        handleDateChange(value) {
            // 日期改变时自动查询
            if (value) {
                this.queryByDate();
            }
        },

        processActionData(data) {
            console.log('开始处理异动解析数据:', data);
            
            if (!Array.isArray(data)) {
                console.error('异动解析数据格式错误: 不是数组格式');
                this.actionData = [];
                return;
            }

            // 按排序号和名称排序
            this.actionData = data.sort((a, b) => {
                if (a.sortNo !== b.sortNo) {
                    return (a.sortNo || 0) - (b.sortNo || 0);
                }
                return a.name.localeCompare(b.name);
            });
            
            // 添加调试信息
            console.log('处理后的异动解析数据:', this.actionData);
            this.actionData.forEach((field, index) => {
                console.log(`板块 ${index}: ${field.name}, 子节点数量: ${field.children ? field.children.length : 0}`);
                if (field.children && field.children.length > 0) {
                    field.children.forEach((child, childIndex) => {
                        console.log(`  子节点 ${childIndex}: ${child.name}`);
                    });
                }
            });
        },
        
        handleNodeClick(data, node, component) {
            console.log('点击树节点:', data);
            
            // 判断是否为叶子节点（股票节点）
            if (data.children && data.children.length === 0) {
                // 这是股票节点，显示股票详情
                this.selectedField = data;
            } else {
                // 这是父节点（领域节点），从actionData中找到完整的领域数据
                this.selectedField = this.actionData.find(field => field.actionFieldId === data.actionFieldId);
                // 父节点点击时也展开/折叠子节点（由于expand-on-click-node="true"，这个会自动处理）
            }
        },
        
        handleNodeExpand(data, node, component) {
            console.log('展开父节点:', data.name);
            // 展开节点时不改变右侧显示
        },
        
        handleNodeCollapse(data, node, component) {
            console.log('折叠父节点:', data.name);
            // 折叠节点时不改变右侧显示
        },
        
        getTotalStockCount() {
            return this.actionData.reduce((total, field) => total + (field.count || 0), 0);
        },
        
        formatStockNodeName(name) {
            // 格式化股票节点名称，高亮连板信息
            // 例如：冠中生态 (sz300948) [2天2板] 
            // 转换为：冠中生态 (sz300948) <span class="lianban-highlight">[2天2板]</span>
            return name.replace(/\[([^\]]+)\]/g, '<span class="lianban-highlight">[$1]</span>');
        }
    },
    
    mounted() {
        // 默认加载当前日期的数据
        this.refreshData();
    }
};